import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:power_distribution_system/model/initapp_model.dart';
import 'package:power_distribution_system/utils/widget/fixedtip_widget.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../bean/selectarealist_bean.dart';
import '../../common/custom_icons.dart';
import '../../common/system_config.dart';
import '../../utils/tools/localstorage_tool.dart';
import '../../utils/tools/screenutil_tool.dart';
import '../../utils/widget/appbar_widget.dart';
import '../../viewmodel/base_vm.dart';
import 'componets/load_statedesc.dart';
import 'componets/not_data.dart';
import 'methods/analysis_theme.dart';
import 'methods/format_data.dart';
import 'methods/open_bottomsheet.dart';
import 'methods/router_switch.dart';

class SelectionareaView extends StatefulWidget {
  @override
  SelectionareaViewState createState() => new SelectionareaViewState();
}

class SelectionareaViewState extends State<SelectionareaView> {
  // 选中台区的内容
  String locationInfo = "请选择台区";

  // 是否为高亮主题
  bool isLight = true;

  // 页面数据列表
  List listContent = [];

  //省市区基础数据
  List areaData = [];

  //数据加载结束开关
  bool falg = true;

  // 网络状态
  bool networkstate;

  // 标记当前app的状态（特指：异常情况0：网络异常  1：WebSocket已断开   2：重连WebSocket）
  int componentState;

  // 统计各项函数被执行的次数
  int implementCount = 0;

  // 请求的参数
  Map<String, dynamic> par = {
    "page": 1,
    "rows": 20,
    "status": 0,
//    "province": "",
//    "city": "",
//    "area": "",
    "areaId": "",
    "name": ""
  };

  //申明上拉加载更多的状态
  RefreshController _refreshController = RefreshController(
    initialRefresh: false,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget("选择台区", isShowRI: false).build(context),
      body: Consumer<InitAppModel>(builder: (context, model, child) {
        // 将网络状态存储为全局状态，便于其他函数访问。（该状态会实时更新）
        networkstate = model.networkstate;

        // 必须保证网络通畅
        if (networkstate) {
          // 标记网络已恢复
          componentState = null;

          // 检查是否为初始化状态
          if (implementCount <= 0) {
            // 发起网络请求，获取页面数据
            initPage(context);

            // 统计执行次数
            implementCount++;
          }
        } else {
          // 标记网络异常
          componentState = 0;

          if (implementCount > 0) {
            // 还原组件初始化状态
            implementCount = 0;
          }
        }

        return Container(
            width: double.infinity,
            height: double.infinity,
            child: Stack(
              children: [
                networkstate
                    ? Container(
                        margin: EdgeInsets.only(top: ST.seth(90)),
                        child: SmartRefresher(
                          enablePullDown: false,
                          enablePullUp: true,
                          controller: _refreshController,
                          onLoading: _onLoading,
                          footer: CustomFooter(
                            builder: (BuildContext context, LoadStatus mode) {
                              Widget body;
                              if (mode == LoadStatus.idle) {
                                body = LoadStateDesc('上拉加载更多...');
                              } else if (mode == LoadStatus.loading) {
                                body = LoadStateDesc("正在玩命加载 . . .",
                                    isLoadComponent: true);
                              } else if (mode == LoadStatus.failed) {
                                body = LoadStateDesc('加载失败！点击重试！');
                              } else if (mode == LoadStatus.canLoading) {
                                body = LoadStateDesc('请松开触碰,加载更多...');
                              } else {
                                body = LoadStateDesc('没有更多数据了...');
                              }
                              return Container(
                                child: Center(child: body),
                              );
                            },
                          ),
                          child: ListView.builder(
                            itemCount: listContent.length,
                            itemBuilder: (BuildContext context, int index) {
                              return InkWell(
                                onTap: () => routerSwitch(
                                    context,
                                    listContent[index].id,
                                    listContent[index].name),
                                child: Container(
                                  decoration: BoxDecoration(
                                      border: Border(
                                          top: BorderSide(
                                              color: SystemConfig.borderColor,
                                              width: ST.seth(1)))),
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                        vertical: ST.seth(15),
                                        horizontal: ST.setw(20)),
                                    color: isLight
                                        ? Theme.of(context).backgroundColor
                                        : Color.fromRGBO(66, 66, 66, 1),
                                    child: Row(
                                      children: [
                                        Expanded(
                                          child: Container(
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  '${listContent[index].name}',
                                                  style: TextStyle(
                                                      fontSize: ST.setsp(30)),
                                                ),
                                                Text(
                                                    '告警数量：${listContent[index].alarmNum != null ? listContent[index].alarmNum : 0}',
                                                    style: TextStyle(
                                                        color: SystemConfig
                                                            .grayColor,
                                                        fontSize: ST.setsp(24)))
                                              ],
                                            ),
                                          ),
                                        ),
                                        Container(
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.end,
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              Container(
                                                decoration: BoxDecoration(
                                                  color: listContent[index]
                                                                  .alarmNum >
                                                              0 &&
                                                          listContent[index]
                                                                  .alarmNum !=
                                                              null
                                                      ? Colors.red
                                                      : null,
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(8)),
                                                ),
                                                //padding: EdgeInsets.all(ST.setw(5)),
                                                padding: EdgeInsets.symmetric(
                                                    vertical: ST.seth(5),
                                                    horizontal: ST.setw(20)),
                                                child: Text("告警",
                                                    style: TextStyle(
                                                        color: Colors.white,
                                                        fontSize:
                                                            ST.setsp(22))),
                                              ),
                                              Icon(Icons.chevron_right,
                                                  size: ST.setsp(46),
                                                  color: SystemConfig.grayColor)
                                            ],
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
                      )
                    : NotData(),
                networkstate
                    ? Visibility(
                        child: InkWell(
                          onTap: () =>
                              openModalBottomSheet(context, areaData, (data) {
                            // 解析选中的台区
                            Map m = formatData(data);

                            print(m);

                            // 更新界面
                            setState(() {
                              locationInfo = m["txt"];
                              par["areaId"] = m["level"] == 4
                                  ? m["areaId"]
                                  : m["areaId"].substring(0, m["level"] * 2);
//                              par["province"] = m["province"];
//                              par["city"] = m["city"];
//                              par["area"] = m["area"];
                              par["page"] = m["page"];
                            });

//                            print(par);

                            // 根据条件再次请求数据
                            initPage(context, isEmpty: true);
                          }),
                          child: Container(
                            width: double.infinity,
                            height: ST.seth(90),
                            margin: EdgeInsets.only(
                                top: model.networkstate ? 0 : ST.seth(76)),
                            padding:
                                EdgeInsets.symmetric(horizontal: ST.setw(30)),
                            decoration: BoxDecoration(
                                color: isLight
                                    ? Theme.of(context).backgroundColor
                                    : Color.fromRGBO(66, 66, 66, 1),
                                boxShadow: [
                                  BoxShadow(
                                      offset: Offset(0, 5),
                                      color: Color.fromRGBO(0, 0, 0, .1),
                                      blurRadius: 5)
                                ]),
                            child: Row(
                              children: [
                                Icon(
                                  CustomIcons.dw,
                                  size: ST.setsp(45),
                                  color: SystemConfig.grayColor,
                                ),
                                Expanded(
                                    child: Text(
                                  "$locationInfo",
                                  style:
                                      TextStyle(color: SystemConfig.grayColor),
                                  textAlign: TextAlign.right,
                                ))
                              ],
                            ),
                          ),
                        ),
                      )
                    : SizedBox.shrink(),
                componentState == null
                    ? SizedBox.shrink()
                    : Positioned(
                        top: 0,
                        left: 0,
                        right: 0,
                        child: FixedTopWidget(componentState),
                      ),
              ],
            ));
      }),
    );
  }

  /// * 上拉加载更多
  void _onLoading() async {
    if (!falg) {
      // 关闭加载更多事件
      _refreshController.loadNoData();
    } else {
      // 拉下后请求数据
      initPage(context);
    }
  }

  /// 初始化组件
  /// * [context] 必填|上下文
  /// * [isEmpty] bool|必填|是否清空数据
  void initPage(BuildContext context, {bool isEmpty = false}) async {
    SelectAreaListBean result;

    // 获取主题信息
    bool isLightTheme = await readTheme();

    // 更新界面
    setState(() {
      listContent = isEmpty ? [] : listContent;
      isLight = isLightTheme;
    });

    //LocalStorage.remove("allArea");

    // 判断areaData中是否已经存在数据
    if (areaData.length <= 0) {
      // 检查省市区数据是否已经存在
      //String allAreaStr = await LocalStorage.getFormat("allArea");
      String allAreaStr = null;

      if (allAreaStr != null) {
        // 将数据转化后赋值
        areaData = json.decode(allAreaStr);

        // 接收后台返回的数据
        result = await BaseVM.getEquipmentList(context, par, openLoad: true);
      } else {
        // 获取省市区基础数据
        // 台区列表
        Map dataAggregate = await BaseVM.concurrentHandle(context, par);

        // 赋值省市区基础数据
        areaData = dataAggregate["allArea"];

        // 赋值台区列表
        result = dataAggregate["areaList"];
      }
    } else {
      // 接收后台返回的数据
      result = await BaseVM.getEquipmentList(context, par, openLoad: false);
    }

    // 完成加载更多通知
    _refreshController.loadComplete();

    // 验证返回的数据
    if (result != null) {
      // ---解构数据中的list
      setState(() {
        listContent.addAll(result.list);
        par["page"] = par["page"] + 1;
      });

      if (listContent.length >= result.total) {
        _refreshController.loadNoData();
        setState(() {
          falg = false;
        });
      }
    } else {
      // 提示没有更多数据了
      _refreshController.loadNoData();
    }
  }
}
